package com.zhiyou.app.shop.website.dao.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Component;

import com.zhiyou.app.shop.common.util.Page;
import com.zhiyou.app.shop.manager.dao.impl.BaseHibernateDAO;
import com.zhiyou.app.shop.website.dao.IStockInfoDao;
import com.zhiyou.app.shop.website.dao.pojo.StockInfo;
import com.zhiyou.app.shop.website.dao.pojo.User;
import com.zhiyou.app.shop.website.dao.pojo.UserStockInfo;

@Component
public class StockInfoDaoImpl extends BaseHibernateDAO<StockInfo, String> implements IStockInfoDao {
	
	public StockInfoDaoImpl(){
		super(StockInfo.class);
	}

	public List<StockInfo> findByNewdate() {
		List<StockInfo> list = hibernateTemplate.execute(new HibernateCallback<List<StockInfo>>() {
			public List<StockInfo> doInHibernate(Session session)
					throws HibernateException {
				String sql = "select * from stock_info order by create_date desc limit 0,1";
			    return session.createSQLQuery(sql).addEntity(StockInfo.class).list();
			}
		});
		return list;
	}

	public List<UserStockInfo> findLasted() {
		List<UserStockInfo> list = hibernateTemplate.execute(new HibernateCallback<List<UserStockInfo>>() {
			public List<UserStockInfo> doInHibernate(Session session)
					throws HibernateException {
				String sql = "select * from user_stock_info order by create_date desc limit 0,1";
				return session.createSQLQuery(sql).addEntity(UserStockInfo.class).list();
			}
		});
		return list;
	}

	public Integer findMaxPeriods() {
		Integer list = hibernateTemplate.execute(new HibernateCallback<Integer>() {
			public Integer doInHibernate(Session session)
					throws HibernateException {
				String sql = "select max(periods) as cnt from stock_info";
				SQLQuery query = session.createSQLQuery(sql);
				Integer total = (Integer)query.addScalar("cnt", new org.hibernate.type.IntegerType()).uniqueResult(); 
				if(total == null){
					return 0;
				}
				return total;
			}
		});
		return list;
	}
}
